package top.withwings.bonus.bonus.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.DateUtils;
import top.withwings.bonus.bonus.pojo.FinalBonus;
import top.withwings.bonus.bonus.repo.FinalBonusRepo;
import top.withwings.bonus.common.pojo.User;
import top.withwings.bonus.common.service.UserService;

import java.util.*;

@Service
public class FinalBonusService {

    @Autowired private UserService userService;
    @Autowired private FinalBonusRepo finalBonusRepo;

    public List<FinalBonus> listBySalesman(String yearMonth){
        List<FinalBonus> finalBonuses = new ArrayList<>();
        for (User user : userService.findAll()) {
            if(user.isAdmin()) continue;
            FinalBonus finalBonus = finalBonusRepo.findOne(user.getId(),yearMonth);
            if(finalBonus == null) continue;
            if(finalBonus.getFinalResult() ==0 && finalBonus.getGrossAmount() ==0) continue;
            finalBonus.setSalesman(user);
            finalBonuses.add(finalBonus);

        }
        return finalBonuses;
    }


    public List<FinalBonus> history(User salesman){
        List<FinalBonus> finalBonuses = new ArrayList<>();
        List<String> yearMonths = calYearMonths();
        for (String yearMonth : yearMonths) {
            FinalBonus finalBonus = finalBonusRepo.findOne(salesman.getId(),yearMonth);
            if(finalBonus == null){
                finalBonus = FinalBonus.createEmptyInstance(yearMonth);
            }
            finalBonus.setSalesman(salesman);
            finalBonuses.add(finalBonus);
        }
        return  finalBonuses;
    }

    private List<String> calYearMonths() {

        List<String> yearMonths = new ArrayList<>();
        Locale china = new Locale("zh", "CN");
        Calendar cal = DateUtils.createToday();
        for (int i = 0; i < 24; i++) {
            cal.add(Calendar.MONTH, -1);
            yearMonths.add(DateUtils.format(cal,"yyyy-MM",china));
        }
        Collections.reverse(yearMonths);
        return yearMonths;
    }

}
